package com.macro.mall.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.macro.mall.bo.AdminUserDetails;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.Assist;
import com.macro.mall.mapper.PmsSiteMapper;
import com.macro.mall.mapper.UmsServiceDeptMapper;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.UmsServiceDept;
import com.macro.mall.model.UmsServiceDeptLog;
import com.macro.mall.service.UmsServiceDeptLogService;
import com.macro.mall.service.UmsServiceDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UmsServiceDept的服务接口的实现类
 *
 * @author gaodx
 */
@Slf4j
@Service
public class UmsServiceDeptServiceImpl implements UmsServiceDeptService {

    private boolean isDebugEnabled;

    @Autowired
    private PmsSiteMapper pmsSiteMapper;

    @Autowired
    private UmsServiceDeptMapper umsServiceDeptMapper;

    @Autowired
    private UmsServiceDeptLogService umsServiceDeptLogService;

    @Override
    public List<UmsServiceDept> find(UmsServiceDept value, Integer pageNum, Integer pageSize) {
        //TODO这里可以做通过Assist做添加查询
        List<UmsServiceDept> result = null;
        Assist assist = new Assist();
        PageHelper.startPage(pageNum, pageSize);
        try {
            if (!StrUtil.isEmpty(value.getDeptName())) {
                assist.andLike("dept_name ", "%" + value.getDeptName() + "%");
            }
            if (!StrUtil.isEmpty(value.getStatus())) {
                assist.andEq("status ", value.getStatus());
            } /*else {
                assist.andNeq("status ", "01");
            }*/
            assist.setOrder(Assist.order("create_time", false));
            result = umsServiceDeptMapper.selectUmsServiceDept(assist);
            if (result.size() > 0) {
                for (UmsServiceDept one : result) {
                    Assist assist1 = new Assist();
                    assist1.andEq("dept_id", one.getId());
                    long pmsSiteRowCount = pmsSiteMapper.getPmsSiteRowCount(assist1);
                    one.setSiteCount(pmsSiteRowCount);
                }
            }
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行获取UmsServiceDept数据集-->结果:", result);
        }
        return result;
    }

    @Override
    public UmsServiceDept findOne(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过UmsServiceDept的id获得UmsServiceDept对象-->失败:id不能为空");
            }
            Asserts.fail("执行通过UmsServiceDept的id获得UmsServiceDept对象-->失败:id不能为空");
        }
        UmsServiceDept result = null;
        try {
            result = umsServiceDeptMapper.selectUmsServiceDeptById(id);
            if (!StrUtil.isBlankIfStr(result)) {
                Assist assist = new Assist();
                assist.andEq("dept_id", result.getId());
                long pmsSiteRowCount = pmsSiteMapper.getPmsSiteRowCount(assist);
                result.setSiteCount(pmsSiteRowCount);
            }
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过UmsServiceDept的id获得UmsServiceDept对象-->结果:", result);
        }
        return result;
    }

    @Override
    public CommonResult saveNotNull(UmsServiceDept value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行将UmsServiceDept中属性值不为null的数据保存到数据库-->失败:对象不能为空");
            }
            Asserts.fail("失败:对象不能为空");
        }
        if (!StrUtil.isBlankIfStr(value.getEndTime()) && !StrUtil.isBlankIfStr(value.getStartTime())) {
            if (value.getEndTime().getTime() < value.getStartTime().getTime()) {
                Asserts.fail("合同开始时间应早于结束时间");
            }
            if (StrUtil.isBlank(value.getStatus())) {
                long l = System.currentTimeMillis();
                if (value.getStartTime().getTime() < l && value.getEndTime().getTime() > l) {
                    value.setStatus("02");
                } else {
                    value.setStatus("01");
                }
            }
        }
        int result = 0;
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            AdminUserDetails memberDetails = (AdminUserDetails) auth.getPrincipal();
            UmsAdmin umsAdmin = memberDetails.getUmsAdmin();
            Long id = umsAdmin.getId();
            String username = umsAdmin.getUsername();
            result = umsServiceDeptMapper.insertNotNullUmsServiceDept(value);
            umsServiceDeptLogService.saveNotNull(UmsServiceDeptLog.builder()
                    .deptId(value.getId())
                    .newStatus(value.getStatus())
                    .operatorId(id + "")
                    .operatorName(username)
                    .type("2")
                    .remarks(value.getRemarks())
                    .build());
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行将UmsServiceDept中属性值不为null的数据保存到数据库-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult updateNotNullById(UmsServiceDept value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过UmsServiceDept的id更新UmsServiceDept中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过UmsServiceDept的id更新UmsServiceDept中属性不为null的数据-->失败:对象为null");
        }
        int result = 0;
        try {
            UmsServiceDept umsServiceDept = umsServiceDeptMapper.selectUmsServiceDeptById(value.getId());
            long sl = System.currentTimeMillis();

            if ("02".equals(value.getStatus())) {
                long stime = umsServiceDept.getStartTime().getTime();
                if (sl < stime) {
                    return CommonResult.failed("未到合作时间无法激活");
                }
                long etime = umsServiceDept.getEndTime().getTime();
                if (sl > etime) {
                    return CommonResult.failed("合作时间已过无法激活");
                }
            }
            if (value.getStartTime().getTime() < sl && value.getEndTime().getTime() > sl) {
                value.setStatus("02");
            } else {
                value.setStatus("01");
            }
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            AdminUserDetails memberDetails = (AdminUserDetails) auth.getPrincipal();
            UmsAdmin umsAdmin = memberDetails.getUmsAdmin();
            result = umsServiceDeptMapper.updateNotNullUmsServiceDeptById(value);
            Long id = umsAdmin.getId();
            String username = umsAdmin.getUsername();
            umsServiceDeptLogService.saveNotNull(UmsServiceDeptLog.builder()
                    .deptId(value.getId())
                    .oldStatus(umsServiceDept.getStatus())
                    .newStatus(value.getStatus())
                    .operatorId(id + "")
                    .operatorName(username)
                    .type("2")
                    .remarks(value.getRemarks())
                    .build());
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过UmsServiceDept的id更新UmsServiceDept中属性不为null的数据-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult updateStatusById(UmsServiceDept value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过UmsServiceDept的id更新UmsServiceDept中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过UmsServiceDept的id更新UmsServiceDept中属性不为null的数据-->失败:对象为null");
        }
        int result = 0;
        try {
            UmsServiceDept umsServiceDept = umsServiceDeptMapper.selectUmsServiceDeptById(value.getId());

            if ("02".equals(value.getStatus())) {
                long stime = umsServiceDept.getStartTime().getTime();
                long sl = System.currentTimeMillis();
                if (sl < stime) {
                    return CommonResult.failed("未到合作时间无法激活");
                }
                long etime = umsServiceDept.getEndTime().getTime();
                long el = System.currentTimeMillis();
                if (el > etime) {
                    return CommonResult.failed("合作时间已过无法激活");
                }
            }
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            AdminUserDetails memberDetails = (AdminUserDetails) auth.getPrincipal();
            UmsAdmin umsAdmin = memberDetails.getUmsAdmin();
            result = umsServiceDeptMapper.updateNotNullUmsServiceDeptById(value);
            Long id = umsAdmin.getId();
            String username = umsAdmin.getUsername();
            umsServiceDeptLogService.saveNotNull(UmsServiceDeptLog.builder()
                    .deptId(value.getId())
                    .oldStatus(umsServiceDept.getStatus())
                    .newStatus(value.getStatus())
                    .operatorId(id + "")
                    .operatorName(username)
                    .type("2")
                    .remarks(value.getRemarks())
                    .build());
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过UmsServiceDept的id更新UmsServiceDept中属性不为null的数据-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult deleteById(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过UmsServiceDept的id删除UmsServiceDept-->失败:id不能为空");
            }
            Asserts.fail("执行通过UmsServiceDept的id删除UmsServiceDept-->失败:id不能为空");
        }
        int result = 0;
        try {
            result = umsServiceDeptMapper.deleteUmsServiceDeptById(id);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过UmsServiceDept的id删除UmsServiceDept-->结果:", result);
        }
        return CommonResult.success(null);
    }
}